#!/bin/sh
#
# The regression-test driver script for the nmea2000 driver.
# CAN is a bit different from normal serial interfaces.
#

GPSD_PORT=2948
CAN_PLAYER=canplayer
CAN_UNIT="vcan0"
BUILD=0

# Requires GNU date extensions
# Should return an empty blank string if those are not present.
STARTTIME=`date +"%s" 2>/dev/null`

# We need to have the build directory in $GPSD_HOME to find the new gpsd
if [ "`dirname $0`" = "." ]; then
    GPSD_HOME=`pwd`
else
    GPSD_HOME=`dirname $0`
fi

version()
{
    echo
    echo `basename $0`" : Version v0.20";
    echo
}

usage()
{
    version;
    echo "usage :" `basename $0` " [-S <portnumber>] [-u <can_device>] [-p <canplayer>] [-b] <testfile>";
    echo "      :" `basename $0` " -v";
    echo "      :" `basename $0` " -h";
    echo "  Options include:";
    echo "  -S <portnumber> = Port for gpsd communication. Default is 2948.";
    echo "  -u <can_device> = Used CAN device. Default is \"vcan0\"";
    echo "  -p <canplayer>  = Programm to replay logfile. Default is \"canplayer\"";
    echo "  -b              = Create testfile.chk instead of checking it.";
    echo "  -v              = Print version and exit.";
    echo "  -h              = Print this helptext and exit.";
    echo "  <testfile>      = A file created by \"candump -l <can_device> ><testfile>\".";
    echo
}

device()
{
    echo
    echo "CAN device \"${CAN_UNIT}\" do not exit."
    echo "Try: sudo ./gpsinit vcan "
    echo
}

can_utils()
(
    echo
    echo "Command to play CAN logfile \"${CAN_PLAYER}\" do not exist."
    echo "Try to install \"can-utils\" from your distribution."
    echo "I your distibution do not provide \"can-utils\", then"
    echo "git clone https://gitorious.org/linux-can/can-utils.git"
    echo "in a directory outside of gpsd, build and install it."
    echo "On most linux systems, \"make\", and then \"sudo make install\" works."
    echo
)

while getopts :S:u:p:vhb opt
do
    case ${opt} in
        S)  GPSD_PORT=${OPTARG};;
        u)  CAN_UNIT=${OPTARG};;
        p)  CAN_PLAYER=${OPTARG};;
        b)  BUILD=1;;
        v)  version; exit 0;;
        h)  usage; exit 0;;
        \?) usage; exit 1;;
    esac
done

shift $((${OPTIND} - 1))

if [ -z $1 ]; then usage; exit 1; fi

TEST_FILE=$1

if [ `ifconfig -a | grep ${CAN_UNIT} | wc -c` -eq 0 ]; then device; exit 1; fi

if [ `command -v ${CAN_PLAYER} | wc -c` -eq 0 ]; then can_utils; exit 1; fi

TMP_PID_FILE=`mktemp`
TMP_OUT_FILE=`mktemp`

${GPSD_HOME}/gpsd -n -G -D0 -S ${GPSD_PORT} -P ${TMP_PID_FILE} nmea2000://${CAN_UNIT}

sleep 1

${GPSD_HOME}/gpspipe -d -r -w -S -o ${TMP_OUT_FILE} :${GPSD_PORT}

sleep 1

${CAN_PLAYER} -I${TEST_FILE} ${CAN_UNIT}=can0

sleep 1

kill `cat ${TMP_PID_FILE}`

sleep 1

if [ ${BUILD} -ne 0 ]
then
    cp ${TMP_OUT_FILE} ${TEST_FILE}.chk
else
    diff ${TEST_FILE}.chk ${TMP_OUT_FILE}
fi

rm -f ${TMP_PID_FILE}
rm -f ${TMP_OUT_FILE}
